package com.pan.service.aspect;


import com.pan.entity.Result;
import com.pan.excep.enume.ErrorCode;
import com.pan.excep.error.ServiceException;
import com.pan.tools.RedisTools;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Aspect
@Component
public class GoodsPriceHistoryAspect {

    @Resource
    private RedisTools redisTools;

    @Pointcut("execution(public * com.pan.service.impl.GoodsPriceHistoryServiceImpl.*(..))")
    public void allCut(){}


    public Integer indexOf(String[] names,String name){
        for (int i=0;i<names.length;i++){
            if (names[i].equals(name)){
                return i;
            }
        }
        return null;
    }

    @Before("allCut()")
    public void checkLogin(JoinPoint joinPoint){
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        String[] names = ms.getParameterNames();
        Integer index = indexOf(names,"adminTicket");
        if (index == null){
            throw new ServiceException(ErrorCode.ASPECT_ERROR);
        }
        String adminTicket = (String) joinPoint.getArgs()[index];
        Result<Boolean> result = redisTools.exists("admin:"+adminTicket);
        if (result==null||!result.getData()){
            throw new ServiceException(ErrorCode.NOT_LOGIN);
        }
    }

}
